﻿using ERPPublic.eneity;
using MediatR;
using PersonnelManagement.Application.Command.PostCommand;
using PersonnelManagement.Domain.Dto;
using PersonnelManagement.Infrstructre.Interface;

namespace PersonnelManagement.Application.CommandHandler.PostCommandHandler
{
    /// <summary>
    /// 部门
    /// </summary>
    public class SectorListCommandHandler : IRequestHandler<SectorListCommand, List<SectorDto>>
    {
        ISectorRepository sRep;

        public SectorListCommandHandler(ISectorRepository sRep)
        {
            this.sRep = sRep;
        }

        public async Task<List<SectorDto>> Handle(SectorListCommand request, CancellationToken cancellationToken)
        {
            List<Sector> categories = (await sRep.Getall()).ToList();
            List<SectorDto> treeCategories = BuildTree(categories, request.SectorId);
            return treeCategories;
        }

        static List<SectorDto> BuildTree(List<Sector> categories, int parentId)
        {
            return categories
                .Where(c => c.Pid == parentId)
                .Select(c => new SectorDto
                {
                    value = (int)c.SectorId,
                    label = c.SectorName,
                    children = BuildTree(categories, (int)c.SectorId) // 递归构建子分类
                })
                .ToList();

        }


    }

}
